import { systemApi } from '/@/api/systemapi'
export var dicMap: Map<string, any> = new Map<string, any>()
export var dicObiect: Map<string, any> = new Map<string, any>()

/**
 * 取数据字典
 */
export const getCodeList = (that: any, newArr: Array<string>) => {
	Promise.all(newArr.map(code => setPromise(code))).then((values) => values.forEach((value, i) => {
		that.dataDictionaryList[newArr[i]] = value
		// that.$set(that.dataDictionaryList, newArr[i], value)
	}))
}

export const setPromise = (codes: string) => {
	return new Promise((resolve, reject) => {
		getDicMap(codes, (res) => {
			resolve(res)
		})
	})
}

/**
 * 返回数据字典
 * @param code 字典编码
 * @param fun 回调方法
 * @returns {Promise<void>}
 */
export async function getDicMap(code: string, fun: Function) {
	if (dicMap[code] === undefined) {
		await getDicText(code, function (data) {
			if ((typeof data === 'object') && data.constructor === Array) {
				var obj = {}
				data.forEach(function (item) {
					if (item.dataCode !== '!') {
						obj[item.dataCode] = ''
						obj[item.dataCode] = item.dataName
					}
				})
				dicMap[code] = obj
				fun(obj)
			}
		})
	} else {
		fun(dicMap[code])
	}
}

/**
 * 数得数据字典文本
 * @param code
 */
export function getDicText(classCode:string, fun:Function) {
	systemApi().getDiclistByClassCode(classCode).then(data => {
		fun(data.list)
	})
}

/**
 * 返回数据字典(排序用)
 * @param code 字典编码
 * @param fun 回调方法
 * @returns {Promise<void>}
 */
export async function getDicObject(code: string, fun: Function) {
	if (dicObiect[code] === undefined) {
		await getDicText(code, function (data) {
			if ((typeof data === 'object') && data.constructor === Array) {
				var arr = []
				data.forEach(function (item) {
					if (item.dataCode !== '!') {
						var obj = {}
						obj.key = item.dataCode
						obj.value = item.dataName
						arr.push(obj)
					}
				})
				dicObiect[code] = arr
				fun(arr)
			}
		})
	} else {
		fun(dicObiect[code])
	}
}